package com.tencent.qcloud.tuikit.tuichat.ui.page;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;

import com.cqyc.network.Response;
import com.cqyc.network.getid.GetMyInformationBox;
import com.cqyc.network.http.HttpUtil;
import com.cqyc.network.http.NConfig;
import com.cqyc.network.model.GoodsInfo;
import com.cqyc.network.model.OrderInfo;
import com.cqyc.network.model.ShopInfo;
import com.cqyc.network.utils.ToastUtils;
import com.cqyc.network.utils.Utils;
import com.google.gson.Gson;
import com.tencent.qcloud.tuicore.TUIConstants;
import com.tencent.qcloud.tuicore.TUICore;
import com.tencent.qcloud.tuikit.tuichat.R;
import com.tencent.qcloud.tuikit.tuichat.TUIChatConstants;
import com.tencent.qcloud.tuikit.tuichat.bean.ChatInfo;
import com.tencent.qcloud.tuikit.tuichat.bean.CustomGoodsMessage;
import com.tencent.qcloud.tuikit.tuichat.bean.CustomHelloMessage;
import com.tencent.qcloud.tuikit.tuichat.bean.CustomOrderMessage;
import com.tencent.qcloud.tuikit.tuichat.bean.InputMoreActionUnit;
import com.tencent.qcloud.tuikit.tuichat.bean.message.TUIMessageBean;
import com.tencent.qcloud.tuikit.tuichat.model.GoodsModel;
import com.tencent.qcloud.tuikit.tuichat.order.OrderListPopup;
import com.tencent.qcloud.tuikit.tuichat.presenter.C2CChatPresenter;
import com.tencent.qcloud.tuikit.tuichat.ui.GoodsList.GoodsListActivity;
import com.tencent.qcloud.tuikit.tuichat.util.ChatMessageBuilder;
import com.tencent.qcloud.tuikit.tuichat.util.TUIChatLog;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;

public class TUIC2CChatFragment extends TUIBaseChatFragment {
    private static final String TAG = TUIC2CChatFragment.class.getSimpleName();

    private ChatInfo chatInfo;
    private C2CChatPresenter presenter;
    private OrderListPopup popup;
    private ShopInfo shopInfo;

    private ActivityResultLauncher<Intent> launcher;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result.getResultCode() == Activity.RESULT_OK && result.getData() != null) {
                Gson gson = new Gson();
                String json = result.getData().getStringExtra("data");
                GoodsInfo goodsInfo = gson.fromJson(json, GoodsInfo.class);
                //发送商品
                CustomGoodsMessage customHelloMessage = new CustomGoodsMessage();
                customHelloMessage.version = TUIChatConstants.version;
                customHelloMessage.item_id = goodsInfo.getItemId();
                customHelloMessage.item_name = goodsInfo.getItemName();
                customHelloMessage.item_img = goodsInfo.getItemImg();
                customHelloMessage.sales_price = goodsInfo.getSalesPrice();
                customHelloMessage.sale_num = goodsInfo.getSaleNum();
                customHelloMessage.live_top = goodsInfo.getLiveTop();
                customHelloMessage.coin_price = goodsInfo.getCoinPrice();
                customHelloMessage.index = goodsInfo.getIndex();
                customHelloMessage.web_url = goodsInfo.getWebUrl();
                customHelloMessage.trade_url = goodsInfo.getTradeUrl();
                String data = gson.toJson(customHelloMessage);
                TUIMessageBean info = ChatMessageBuilder.buildCustomMessage(data, "商品", null);
                chatView.sendMessage(info, false);
            }
        });
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        TUIChatLog.i(TAG, "oncreate view " + this);

        baseView = super.onCreateView(inflater, container, savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle == null) {
            return baseView;
        }
        chatInfo = (ChatInfo) bundle.getSerializable(TUIChatConstants.CHAT_INFO);
        if (chatInfo == null) {
            return baseView;
        }

        initView();

        return baseView;
    }

    @Override
    protected void initView() {
        super.initView();

        GoodsModel goodsModel = null;
        Bundle bundle = getArguments();
        if (bundle != null) {
            Serializable serializable = bundle.getSerializable(GoodsModel.TAG);
            if (serializable != null) {
                goodsModel = (GoodsModel) serializable;
            }
        }
        chatView.setGoodsView(goodsModel);

        chatView.setPresenter(presenter);
        presenter.setChatInfo(chatInfo);
        presenter.setTypingListener(chatView.mTypingListener);
        chatView.setChatInfo(chatInfo);
        //菜单
        if (GetMyInformationBox.INSTANCE.isBuyer()) {
            //chatView.getTitleBar().setRightIcon(TUIThemeManager.getAttrResId(getContext(), R.attr.chat_title_bar_more_menu));
            chatView.getTitleBar().setRightIcon(R.drawable.ic_setting);
        } else {
            chatView.getTitleBar().setRightIcon(R.drawable.ic_setting2);
        }
        titleBar.setOnRightClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Bundle bundle = new Bundle();
//                bundle.putString(TUIConstants.TUIChat.CHAT_ID, chatInfo.getId());
//                TUICore.startActivity("FriendProfileActivity", bundle);
                if (GetMyInformationBox.INSTANCE.isBuyer()) {
                    if (shopInfo == null) {
                        getMchInfo(2);
                    } else {
                        Bundle bundle = new Bundle();
                        bundle.putString(TUIConstants.TUIChat.CHAT_ID, chatInfo.getId());
                        bundle.putString("shopInfo", new Gson().toJson(shopInfo));
                        TUICore.startActivity("ChatSettingActivity", bundle);
                    }
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putString(TUIConstants.TUIChat.CHAT_ID, chatInfo.getId());
                    TUICore.startActivity("ChatSettingActivity2", bundle);
                }
            }
        });

        //买家要显示店铺
        if (GetMyInformationBox.INSTANCE.isBuyer()) {
            chatView.getTitleBar().setShoppingIcon(R.drawable.ic_shopping);
            chatView.getTitleBar().setShoppingClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (shopInfo == null) {
                        getMchInfo(1);
                    } else {
                        Bundle bundle = new Bundle();
                        Map<String, String> map = new HashMap<>();
                        map.put("token", GetMyInformationBox.INSTANCE.getToken());
                        map.put("app_id", GetMyInformationBox.INSTANCE.getAppId());
                        map.put("android_version_code", GetMyInformationBox.INSTANCE.getVersion());
                        map.put("platform", "2");

                        String path = Utils.Companion.buildUrl(shopInfo.getStoreDetailUrl(), map);
                        bundle.putString(NConfig.Companion.getWebViewUrl(), path);
                        bundle.putBoolean(NConfig.Companion.getWebViewTitleVisible(), false);
                        TUICore.startActivity(NConfig.Companion.getWebName(), bundle);
                    }
                }
            });
        }

        //情况特殊在这里添加菜单
        InputMoreActionUnit unit = new InputMoreActionUnit() {
        };
        unit.setIconResId(R.drawable.order);
        unit.setTitleId(R.string.order);
        unit.setActionId(CustomHelloMessage.CUSTOM_HELLO_ACTION_ID);
        unit.setPriority(10);
        unit.setOnClickListener(unit.new OnActionClickListener() {
            @Override
            public void onClick() {
                getGoodsList(chatView);
            }
        });
        chatView.getInputLayout().addAction(unit);

        //买家不显示商品
        if (!GetMyInformationBox.INSTANCE.isBuyer()) {
            unit = new InputMoreActionUnit() {
            };
            unit.setIconResId(R.drawable.group);
            unit.setTitleId(R.string.group);
            unit.setActionId(CustomHelloMessage.CUSTOM_HELLO_ACTION_ID);
            unit.setPriority(10);
            unit.setOnClickListener(unit.new OnActionClickListener() {
                @Override
                public void onClick() {
                    Intent intent = new Intent(getContext(), GoodsListActivity.class);
                    intent.putExtra("id", chatInfo.getId());
                    launcher.launch(intent);
                }
            });
            chatView.getInputLayout().addAction(unit);
        }
        //--------------------------

        if (GetMyInformationBox.INSTANCE.isBuyer()) {
            getMchInfo(0);
        }
    }

    /**
     * 获取商家信息
     *
     * @param type 区分这次接口请求之后要做的事
     */
    private void getMchInfo(int type) {
        String mchId = chatInfo.getId();
        mchId = NConfig.Companion.getRealId(mchId);
        HttpUtil.api.findMchInfo(mchId).enqueue(new Callback<Response<ShopInfo>>() {
            @Override
            public void onResponse(Call<Response<ShopInfo>> call, retrofit2.Response<Response<ShopInfo>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    shopInfo = response.body().getData();
                    if (shopInfo != null)
                        GetMyInformationBox.INSTANCE.setCanSender(shopInfo.getImOpen() == 1);
                }
                if (type == 1) {
                    Bundle bundle = new Bundle();
                    Map<String, String> map = new HashMap<>();
                    map.put("token", GetMyInformationBox.INSTANCE.getToken());
                    map.put("app_id", GetMyInformationBox.INSTANCE.getAppId());
                    map.put("android_version_code", GetMyInformationBox.INSTANCE.getVersion());
                    map.put("platform", "2");

                    String path = Utils.Companion.buildUrl(shopInfo.getStoreDetailUrl(), map);
                    bundle.putString(NConfig.Companion.getWebViewUrl(), path);
                    TUICore.startActivity(NConfig.Companion.getWebName(), bundle);
                } else if (type == 2) {
                    Bundle bundle = new Bundle();
                    bundle.putString(TUIConstants.TUIChat.CHAT_ID, chatInfo.getId());
                    bundle.putString("shopInfo", new Gson().toJson(shopInfo));
                    bundle.putBoolean(NConfig.Companion.getWebViewTitleVisible(), false);
                    TUICore.startActivity("ChatSettingActivity", bundle);
                }
            }

            @Override
            public void onFailure(Call<Response<ShopInfo>> call, Throwable t) {

            }
        });
    }

    //显示订单列表
    private void getGoodsList(View view) {
        if (popup == null) {
            popup = new OrderListPopup(getContext());
        }
        popup.setOrderClickListener(new OrderListPopup.OrderClickListener() {
            @Override
            public void onClick(int position, OrderInfo.ListBean data) {
                Log.e("GetGoodsList", "发送订单信息");
                //点击订单，发送订单信息
                Gson gson = new Gson();
                CustomOrderMessage customOrderMessage = new CustomOrderMessage();
                customOrderMessage.version = TUIChatConstants.version;
                customOrderMessage.setId(data.getId());
                customOrderMessage.setUid(data.getUid());
                customOrderMessage.setTrade_items(data.getTrade_items());
                customOrderMessage.setTrade_sn(data.getTrade_sn());
                customOrderMessage.setCreated_at(data.getCreated_at());
                customOrderMessage.setTrade_status(data.getTrade_status());
                customOrderMessage.setTrade_status_desc(data.getTrade_status_desc());
                customOrderMessage.setTrade_user(data.getTrade_user());
                customOrderMessage.setPayment(data.getPayment());
                customOrderMessage.setTrade_web_url(data.getTrade_web_url());
                customOrderMessage.setTrade_items(data.getTrade_items());
                TUIMessageBean info = ChatMessageBuilder.buildCustomMessage(gson.toJson(customOrderMessage), "订单", null);
                chatView.sendMessage(info, false);
            }
        });
        Call<Response<OrderInfo>> call;
        if (GetMyInformationBox.INSTANCE.isBuyer()) {
            String uId = NConfig.Companion.getRealId(chatInfo.getId());
            popup.setUid(uId);
            call = HttpUtil.api.tradeListBuy(uId, 1, "20");
        } else {
            String uId = NConfig.Companion.getRealId(chatInfo.getId());
            popup.setUid(uId);
            call = HttpUtil.api.tradeList(uId, 1, "20");
        }
        call.enqueue(new Callback<Response<OrderInfo>>() {
            @Override
            public void onResponse(Call<Response<OrderInfo>> call, retrofit2.Response<Response<OrderInfo>> response) {
                if (response.isSuccessful()) {
                    Response<OrderInfo> result = response.body();
                    if (result != null && result.getData() != null) {
                        if (result.getCode() == 2000) {
                            popup.setView(result.getData().getList());
                        }
                    }
                } else {
                    popup.setView(null);
                    ToastUtils.showLong(getContext(), "没有订单!");
                }
                popup.show(view);
            }

            @Override
            public void onFailure(Call<Response<OrderInfo>> call, Throwable t) {
                ToastUtils.showLong(getContext(), "获取订单异常请重试!");
            }
        });
    }

    public void setPresenter(C2CChatPresenter presenter) {
        this.presenter = presenter;
    }

    @Override
    public C2CChatPresenter getPresenter() {
        return presenter;
    }

    @Override
    public ChatInfo getChatInfo() {
        return chatInfo;
    }
}
